﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
using System.IO;
using ZXing;

namespace CommandLib
{
    /// <summary>
    /// 跨平台图片处理
    /// </summary>
    public sealed class ImageHelper
    {
        /// <summary>
        /// base64转图片
        /// </summary>
        /// <param name="imgstr"></param>
        /// <returns></returns>
        public static Image Base64ToImg(string imgstr)
        {

            if (!string.IsNullOrEmpty(imgstr))
            {
                var imgdata = Convert.FromBase64String(imgstr);
                return Image.Load(imgdata);
            }
            else
                return null;

        }
        /// <summary>
        /// 图片加载
        /// </summary>
        /// <param name="fileroot"></param>
        /// <returns></returns>
        public static Image LoadImg(string fileroot)
        {
            if (File.Exists(fileroot))
            {
                return Image.Load(fileroot);
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 图片转Base64
        /// </summary>
        /// <param name="image">图片对象</param>
        /// <param name="imageFormat"></param>
        /// <returns></returns>
        public static string ImgToBase64(Image image, IImageFormat imageFormat = null)
        {

            if (image != null)
            {
                if (imageFormat == null)
                {
                    imageFormat = JpegFormat.Instance;
                }
                using (var memoryStream = new MemoryStream())
                {
                    image.Save(memoryStream, imageFormat);
                    memoryStream.TryGetBuffer(out ArraySegment<byte> buffer);
                    return Convert.ToBase64String(buffer.Array, 0, (int)memoryStream.Length);
                }
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 流转图片
        /// </summary>
        /// <param name="bts"></param>
        /// <returns></returns>
        public static Image BytesToImage(byte[] bts)
        {

            if (bts.Length > 0)
            {
                return Image.Load(bts);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 图片转流
        /// </summary>
        /// <param name="image"></param>
        /// <param name="imageFormat"></param>
        /// <returns></returns>
        public static byte[] ImgToBytes(Image image, IImageFormat imageFormat = null)
        {

            if (image != null)
            {
                if (imageFormat == null)
                {
                    imageFormat = JpegFormat.Instance;
                }
                using (var memoryStream = new MemoryStream())
                {
                    image.Save(memoryStream, imageFormat);
                    memoryStream.TryGetBuffer(out ArraySegment<byte> buffer);
                    return buffer.ToArray();

                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="image">图片对面象</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <returns></returns>
        public static Image ScanImage(Image image, int width, int height)
        {

            if (image != null)
            {
                var size = ResizeImage(image, width, height);
                image.Mutate(h => h.Resize(size.Width, size.Height));
                return image;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 跨平台生成二维码
        /// </summary>
        /// <param name="value">生成内容</param>
        /// <param name="width">二维码宽，默认500</param>
        /// <param name="height">二维码高，默认500</param>
        public static Image CreateQrCode(string value, int width = 500, int height = 500)
        {
            var writer = new ZXing.ImageSharp.BarcodeWriter<Rgba32>
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions
                {
                    DisableECI = true,
                    CharacterSet = "UTF-8",
                    Width = width,
                    Height = height,
                    Margin = 1
                }
            };
            var image = writer.WriteAsImageSharp<Rgba32>(value);
            var ms = new MemoryStream();
            image.Save(ms, new PngEncoder());
            return Image.Load(ms);
        }


        /// <summary>
        /// 计算大小
        /// </summary>
        /// <param name="img"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <returns></returns>
        private static ImgSize ResizeImage(Image img, int maxWidth, int maxHeight)
        {
            ImgSize result = new ImgSize();
            if (img.Width > maxWidth || img.Height > maxHeight)
            {
                double widthRatio = (double)img.Width / (double)maxWidth;
                double heightRatio = (double)img.Height / (double)maxHeight;
                double ratio = Math.Max(widthRatio, heightRatio);
                result.Width = (int)(img.Width / ratio);
                result.Height = (int)(img.Height / ratio);
            }
            else
            {
                result.Width = img.Width;
                result.Height = img.Height;

            }
            return result;
        }

        public struct ImgSize
        {
            public int Height;

            public int Width;

        }
    }
}
